import { Button, Space, Spin, message } from "antd";
import { ControlType as TYPE } from "@components";
import { useMainContext } from '@contexts/MainContext'
import { useState, useRef } from "react";
import { RULE_REQUIRED } from "@rules";
import { findWeatherTypeGrade, findUnitArea, findUnitRisks } from "@apis/indexApi";

const checkPrice = (_, value) => {
  const {subjectCountStart: Start, subjectCountEnd: End} = value
  if (Start > End) {
    return Promise.reject(new Error('范围初始值不能大于结束值'));
  }
  return Promise.resolve();
};

export const useFields = () => {

  const queryFormRef = useRef("queryFormRef");
  const modalFormRef = useRef("modalFormRef");
  const modalRef = useRef("modalRef");
  const [WeatherTypes, setWeatherTypes] = useState([])
  const [unitAreas, setUnitAreas] = useState([])
  const [unitRisks, setUnitRisks] = useState([])
  const [labelLoading, setLabelLoading] = useState(false)

  const findWeatherType = async (formRef) => {
      setWeatherTypes([])
      const weatherType = formRef.current?.getFieldValue('weatherType')
      if (!weatherType) return message.error('请先选择天气类型')

      setLabelLoading(true)
      const newWeatherTypes = await findWeatherTypeGrade({weatherType})
      setLabelLoading(false)
      setWeatherTypes(newWeatherTypes)
      modalRef.current.setModalLoading(false)
  }

  const getUnitArea = async (formRef, row) => {
    setUnitAreas([])
    const unitCode = formRef.current?.getFieldValue('unitCode')
    if (!unitCode) return message.error('请先选择机构')

    setLabelLoading(true)
    const newUnitAreas = await findUnitArea(unitCode)
    setLabelLoading(false)
    setUnitAreas(newUnitAreas)

    if (!row) return
    const { realRiskAreaIdList } = row
    const newValue = realRiskAreaIdList?.length === newUnitAreas?.length ? ['all'] : realRiskAreaIdList
    modalFormRef.current?.setFieldValue('untrueRealRiskAreaIdList', newValue)
  }

  const getUnitRisks = async (formRef, row) => {
    setUnitRisks([])
    const unitCode = formRef.current?.getFieldValue('unitCode')
    if (!unitCode) return message.error('请先选择机构')

    setLabelLoading(true)
    const newUnitRisks = await findUnitRisks(unitCode)
    setLabelLoading(false)
    setUnitRisks(newUnitRisks)

    if (!row) return
    const { productCodeList } = row
    const newValue = productCodeList?.length === newUnitRisks?.length ? ['all'] : productCodeList
    modalFormRef.current?.setFieldValue('untrueProductCodeList', newValue)
  }

  const selectConfig = (name, label, codeKey) => {
    return {
      name,
      label,
      codeKey,
      controlType: TYPE.SELECT,
      allowClear: true,
      showSearch: true,
      optionFilterProp: "children",
      filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
      notFoundContent: labelLoading ? <Spin size="small" /> : null,
    }
  }

  const fields = [
    { 
      ...selectConfig('unitCode','归属机构','userAuthUnits'),
      onSelect: (value, option) => {
        if (!option?.value) return
        queryFormRef.current?.setFieldValue('productCode', null)
      },
      onClear: () => {
        queryFormRef.current?.setFieldValue('productCode', null)
      }
    }, 
    { 
      options: unitRisks,
      ...selectConfig('productCode','产品类型'), 
      controlType: TYPE.SELECTBOTH,
      onFocus: () => getUnitRisks(queryFormRef)
    }, 
    { 
      ...selectConfig('weatherType','天气类型','WeatherType'),
      onSelect: (value, option) => {
        if (!option?.value) return
        queryFormRef.current?.setFieldsValue({ ...queryFormRef.current?.getFieldValue(), weatherTypeGrade: null })
      },
      onClear: () => {
        queryFormRef.current?.setFieldsValue({ ...queryFormRef.current?.getFieldValue(), weatherTypeGrade: null })
      }
    },
    { 
      options: WeatherTypes,
      ...selectConfig('weatherTypeGrade','天气类型等级'),
      onFocus: () => findWeatherType(queryFormRef)
    },
    { ...selectConfig('realRiskRank','风险等级','RiskGradeType') },
    { name: 'unitAreaName', label: "受灾区域", controlType: TYPE.INPUT },
    { name: 'subjectCount', label: '受灾标数量', controlType: TYPE.INPUT_NUMBER_RANGE, linkageFields: ['subjectCountStart', 'subjectCountEnd'], rules: [{validator: checkPrice}] },
    { name: 'abnormalWeatherTime', label: '受灾时间', controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ['abnormalWeatherTimeStart', 'abnormalWeatherTimeEnd'], showTime: true },
    // { ...selectConfig("status","状态","status") },
  ];

  const modalFields = [
    { name: 'unitName', label: '机构名称', controlType: TYPE.INPUT, mode: 'hidden' },
    { name: 'weatherTypeName', label: '天气类型名称', controlType: TYPE.INPUT, mode: 'hidden' },
    { 
      ...selectConfig('unitCode','归属机构','userAuthUnits'),
      rules: [RULE_REQUIRED],
      onSelect: (value, option) => {
        if (!option?.value) return
        modalFormRef.current?.setFieldValue('unitName', option.children)
        modalFormRef.current?.setFieldValue('productCode', null)
        modalFormRef.current?.setFieldValue('realRiskAreaId', null)
      },
      onClear: () => {
        modalFormRef.current?.setFieldValue('productCode', null)
        modalFormRef.current?.setFieldValue('realRiskAreaId', null)
      }
    },
    { 
      options: unitRisks,
      ...selectConfig('untrueProductCodeList','产品类型'),
      selectmode: "multiple",
      rules: [RULE_REQUIRED],
      controlType: TYPE.SELECTALL,
      onChange: (value, option=[], allValue) => {
          modalFormRef.current?.setFieldValue('productCodeList', allValue || value)
          modalFormRef.current?.setFieldValue('productTypeList', option.map(item => item.children))
      },
      onFocus: () => getUnitRisks(modalFormRef)
  }, 
  { 
      options: [],
      ...selectConfig('productCodeList','产品类型'),
      selectmode: "multiple",
      mode: 'hidden'
  }, 
    { 
      ...selectConfig('productTypeList','产品类型Str'),
      selectmode: "multiple",
      mode: 'hidden'
    },
    {
      options: unitAreas, 
      ...selectConfig('untrueRealRiskAreaIdList','受灾区域'),
      rules: [RULE_REQUIRED],
      controlType: TYPE.SELECTALL,
      onChange: (value, option=[]) => {
        modalFormRef.current?.setFieldValue('realRiskAreaIdList', option.map(item => item.value))
        modalFormRef.current?.setFieldValue('realRiskAreaNameList', option.map(item => item.children))
      },
      onFocus: () => getUnitArea(modalFormRef),
      optionTemplate: option => <>{option.label}</>
    },
    { 
      options: [],
      ...selectConfig('realRiskAreaIdList','受灾区域'),
      selectmode: "multiple",
      mode: 'hidden'
  }, 
    { 
      ...selectConfig('realRiskAreaNameList','受灾区域Str'),
      selectmode: "multiple",
      mode: 'hidden'
    },
    { 
      ...selectConfig('weatherType','天气类型','WeatherType'),
      rules: [RULE_REQUIRED],
      onSelect: (value, option) => {
        if (!option?.value) return
        modalFormRef.current?.setFieldValue('weatherTypeGrade', null)
        modalFormRef.current?.setFieldValue('weatherTypeName', option.children)
        setWeatherTypes([])
      },
    },
    { 
      options: WeatherTypes,
      ...selectConfig('weatherTypeGrade','天气类型等级'),
      rules: [RULE_REQUIRED],
      onFocus: () => findWeatherType(modalFormRef)
    },
    { ...selectConfig('cfgRiskRank','风险等级','RiskGradeType'), rules: [RULE_REQUIRED] },
    { name: 'subjectCount', label: '受灾标数量', controlType: TYPE.INPUT_NUMBER },
    { name: 'abnormalWeatherTime', label: '受灾时间', controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ['abnormalWeatherTimeStart', 'abnormalWeatherTimeEnd'], showTime: true, rules: [RULE_REQUIRED] },
    // { ...selectConfig("status","状态","status"), rules: [RULE_REQUIRED] },
  ];

  const getWeatherTypeUnitAreaUnitRisks = (row) => {
    modalRef.current.setModalLoading(true)
    setTimeout(() => {
      getUnitRisks(modalFormRef, row)
      getUnitArea(modalFormRef, row)
      findWeatherType(modalFormRef)
    }, 0);
  }

  return {
    queryFormRef,
    fields,
    modalRef,
    modalFormRef,
    modalFields,
    getWeatherTypeUnitAreaUnitRisks
  }
}

export const GetColumns = (editFun) => {
  const { isButtomShow } = useMainContext()

  return [
    { title: '应急事项', dataIndex: 'emerName', key: 'emerName', open: true, width: 200 },
    { title: '归属机构', dataIndex: 'unitName', key: 'unitName', open: true, width: 200 },
    { title: '产品类型', dataIndex: 'productTypeStr', key: 'productTypeStr', open: true, width: 200 },
    { title: '天气类型', dataIndex: 'weatherTypeName', key: 'weatherTypeName', open: true, width: 100 },
    { title: '天气类型等级', dataIndex: 'weatherTypeGradeName', key: 'weatherTypeGradeName', open: true, width: 120 },
    { title: '风险等级', dataIndex: 'cfgRiskRankName', key: 'cfgRiskRankName', open: true, width: 100 },
    { title: '受灾区域名称', dataIndex: 'realRiskAreaNameStr', key: 'realRiskAreaNameStr', open: true, width: 200 },
    { title: '受灾标数量', dataIndex: 'subjectCount', key: 'subjectCount', open: true, width: 120 },
    { title: '受灾起止时间', dataIndex: 'abnormalWeatherTime', key: 'abnormalWeatherTime', open: true, width: 320,
      render: (_, record) => {
        return (
          <span>{record.abnormalWeatherTimeStart+' ~ '+record.abnormalWeatherTimeEnd}</span>
        )
      }
    },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', open: true, width: 200 },
    {
      title: "操作",
      dataIndex: 'operationCol',
      key: 'operationCol',
      open: true, width: 100,
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            {isButtomShow('280102') && <Button type="primary" onClick={() => editFun(record)}>编辑</Button>}
          </Space>
        )
      }
    }
  ]
}